package com.base.cn.platform.os.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * 对象和字节数组相互转换工具类
 */
public class ObjectByteUtil {
    private final Logger LOGGER = LoggerFactory.getLogger(ObjectByteUtil.class);
    /**
     * 把字节数组转成对象
     * @param bytes 字节数据
     * @return 转换后的对象
     */
    public Object byteToObject(byte[] bytes){
        Object obj = null;
        if(ObjectUtils.isNotEmpty(bytes)){
            ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
            try {
                ObjectInputStream oi = new ObjectInputStream(bi);
                obj = oi.readObject();
                bi.close();
                oi.close();
            } catch (Exception e) {
                LOGGER.error("byteToObject()",e);
            }
        }
        return obj;
    }

    /**
     * 将对象转换成字节数组对象
     * @param obj 要转换的对象
     * @return 转换后的数组
     */
    public byte[] objectToByte(Object obj){
        byte[] bytes = null;
        if(obj!=null){
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            try {
                ObjectOutputStream oo = new ObjectOutputStream(bo);
                oo.writeObject(obj);
                bytes = bo.toByteArray();
            } catch (Exception e) {
                LOGGER.error("objectToByte()",e);
            }
        }

        return bytes;
    }

}
